<template>
  <div class="experience" :class="{ 'random-mode': isRandom }">
    <RandomModeBar 
      v-if="isRandom"
      :writer-name="writer?.name"
    />

    <div v-if="writer">
      <div class="author-section">
        <div class="author-container">
          <img :src="getAvatar(writer.avatar_path)" class="author-img" :alt="writer.name">
          <h1 class="author-name">
            <img v-if="isRandom" src="@/assets/img/random.png" class="random-icon" alt="随机">
            {{ writer.name }}
          </h1> 
        </div>
      </div>

      <div class="middle">
        <h1>生平简介</h1>
        <div class="experience-content">
          <p 
            class="experience-paragraph"
            v-for="(paragraph, index) in splitExperience"
            :key="index"
          >
            {{ paragraph }}
          </p>
        </div>
        <div class="action-buttons" v-if="isRandom">
          <button class="btn explore-btn" @click="viewWorks">查看此作家作品</button>
          <button class="btn explore-btn" @click="viewQuotes">查看此作家名言</button>
        </div>

        <div v-else class="action-buttons">
          <div class="button-row">
            <button class="btn explore-btn" @click="viewWorks(false)">查看此作家作品</button>
            <button class="btn explore-btn" @click="viewQuotes(false)">查看该作家名言</button>
          </div>
          <div class="button-row button-row-second">
            <template v-if="isAdmin">
              <button class="btn explore-btn" @click="editWriter">修改作家信息</button>
              <button class="btn explore-btn" @click="addWork">增加该作家作品</button>
              <button class="btn explore-btn" @click="showDeleteConfirm = true">删除该作家</button>
            </template>
            <template v-else-if="isUploader">
              <button class="btn explore-btn" @click="editWriter">修改作家信息</button>
              <button class="btn explore-btn" @click="addWork">增加该作家作品</button>
            </template>
            <template v-else>
              <button class="btn explore-btn" @click="addWork">增加该作家作品</button>
            </template>
          </div>
        </div>
      </div>
    </div>

    <!-- 使用新的删除弹窗组件 -->
    <DeleteModal
      :visible="showDeleteConfirm"
      type="confirm"
      title="确认删除作家"
      :message="`作家名称：${writer?.name}<br>上传用户：${writer?.username || '未知用户'}`"
      @confirm="confirmDelete"
      @cancel="showDeleteConfirm = false"
      @close="showDeleteConfirm = false"
    />

    <DeleteModal
      :visible="showDeleteSuccess"
      type="success"
      title="删除成功"
      message="删除成功。"
      redirect-text="主页面"
      :countdown="5"
      @redirect="goHome"
      @close="goHome"
    />
  </div>
</template>

<script>
import RandomModeBar from '@/components/RandomModeBar.vue'
import DeleteModal from '@/components/DeleteModal.vue'

export default {
  name: 'Experience',
  components: {
    RandomModeBar,
    DeleteModal
  },
  props: {
    isRandom: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      writer: null,
      isAdmin: false,
      showDeleteConfirm: false,
      showDeleteSuccess: false
    }
  },
  computed: {
    splitExperience() {
      return this.writer?.experience?.split('\n').filter(p => p.trim()) || []
    },
    isUploader() {
      const userId = String(localStorage.getItem('userId'))
      return this.writer && String(this.writer.user_id) === userId
    },
    canEdit() {
      return this.isAdmin || this.isUploader
    }
  },
  methods: {
    getAvatar(path) {
      if (!path) return require('@/assets/img/Literature Trace.png')
      if (typeof path === 'string' && path.startsWith('/img/')) {
        return `http://localhost:3000${path}`
      }
      try {
        return require(`@/assets/img/${path}`)
      } catch {
        return require('@/assets/img/Literature Trace.png')
      }
    },
    async fetchWriter() {
      try {
        const response = await this.$axios.get(`/api/writers/${this.$route.params.id}`)
        this.writer = response.data
      } catch (error) {
        console.error('获取作家信息失败：', error)
      }
    },
    viewWorks(isRandom = true) {
      if (isRandom) {
        this.$router.push(`/works/${this.writer.id}?mode=random`)
      } else {
        this.$router.push(`/works/${this.writer.id}`)
      }
    },
    viewQuotes(isRandom = true) {
      if (isRandom) {
        this.$router.push(`/quotes/${this.writer.id}?mode=random`)
      } else {
        this.$router.push(`/quotes/${this.writer.id}`)
      }
    },
    editWriter() {
      this.$router.push(`/edit-writer/${this.writer.id}`)
    },
    addWork() {
      this.$router.push(`/edit-work?writerId=${this.writer.id}&from=${encodeURIComponent(this.$route.fullPath)}`)
    },
    async confirmDelete() {
      try {
        await this.$axios.delete(`/api/writers/${this.writer.id}`)
        this.showDeleteConfirm = false
        this.showDeleteSuccess = true
      } catch (error) {
        alert('删除失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    goHome() {
      this.showDeleteSuccess = false
      this.$router.push('/home')
    }
  },
  created() {
    this.fetchWriter()
    const userRole = localStorage.getItem('userRole')
    this.isAdmin = userRole === '1'
  }
}
</script>

<style scoped>
.experience {
  padding-top: 0;
}

.author-section {
  width: 100%;
  text-align: center;
  margin: 20px 0 5px;
}

.author-img {
  width: 180px;
  height: 220px;
  border-radius: 50%;
  object-fit: cover;
  display: block;
  margin: 0 auto 20px;
}

.author-name {
  font-size: 2em;
  color: #333;
  margin: 0 0 5px;
  font-family: "Noto Sans SC", "Microsoft YaHei", "PingFang SC", Arial, "Helvetica Neue", Helvetica, sans-serif;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
}

.random-icon {
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

.middle {
  width: 900px;
  min-height: 900px;
  background: rgba(255, 255, 255, 0.4);
  margin: auto;
  margin-top: 10px;
  border-radius: 5%;
  padding: 20px;
  box-sizing: border-box;
}

.middle h1 {
  text-align: center;
  padding-bottom: 10px;
  border-bottom: #3F6580 solid 1px;
  margin: 0 8px 20px;
}

.experience-content {
  padding: 0 20px;
}

.experience-paragraph {
  margin-left: 20px;
  font-size: 15px;
  font-weight: 400;
  font-family: "Noto Sans SC", "Microsoft YaHei", "PingFang SC", Arial, "Helvetica Neue", Helvetica, sans-serif;
  line-height: 1.8;
  margin-bottom: 10px;
  color: #333;
}

.action-buttons {
  text-align: center;
  margin: 30px 0;
}

.btn {
  padding: 8px 25px;
  margin: 0 10px;
  border: none;
  border-radius: 4px;
  font-size: 0.9em;
  cursor: pointer;
  transition: all 0.3s ease;
}

.explore-btn {
  background: none;
  border: 1px solid #166d80;
  color: #166d80;
  border-radius: 15px;
}

.explore-btn:hover {
  background-color: #166d80;
  color: white;
}

.edit-btn {
  background-color: #42b983;
  color: white;
}

.add-btn {
  background-color: #4a90e2;
  color: white;
}

.delete-btn {
  background-color: #e74c3c;
  color: white;
}

.delete-btn:hover {
  background-color: #b71c1c;
  color: white;
}

.btn:not(.delete-btn):hover {
  background-color: #166d80;
  color: white;
}

.button-row.button-row-second {
  margin-top: 20px;
}
</style>
